<?php
/**
 * Created by PhpStorm.
 * User: qingyun
 * Date: 17/4/11
 * Time: 下午7:13
 */

function _md5($str, $salt){
    return md5($salt . md5($salt . $str . $salt) . $salt);
}

function _getSalt($num){
    $saltArr = array('~','!','@','#','$','%','^','&','*');
    $salt = '';
    for($i = 0;$i < $num; $i++){
        $str = $saltArr[array_rand($saltArr,1)];
        $salt .= $str;
    }
    return $salt;
}

function _getDate($type = 1, $time = 0){
    $dateTime = '';
    switch($type){
        case 1;
            $dateTime = date('Y-m-d H:i:s');
            break;
        case 2;
            $dateTime = time();
            break;
        case 3;
            $dateTime = date('Y-m-d H:i:s', $time);
            break;
        case 4;
            $dateTime = strtotime($time);
            break;
        default;
            return false;
    }
    return $dateTime;
}

function uploadFile($fileDATA,$filePath = 'Upload/head/'){
    if(empty($fileDATA)){
        return ['status' => 1, 'msg' => '没有上传图片！'];
    }
    $typeArr = ['image/jpeg','image/png','image/jpg','image/gif','image/ico'];
    if(!in_array($fileDATA['type'],$typeArr)){
        return ['status' => 1, 'msg' => '图片不符合要求！'];
    }
    if($fileDATA['size'] > 1024 * 1024 * 200){
        return ['status' => 1, 'msg' => '图片超过了允许的大小！'];
    }
    $fileName = microtime(true).'.'.end(explode('.',$fileDATA['name']));
    if(!is_dir($filePath) && !is_writable($filePath)){
        return ['status' => 1, 'msg' => '文件夹存储异常！'];
    }
    $litPath = $filePath.$fileName;
    if(!move_uploaded_file($fileDATA['tmp_name'],$litPath)){
        return ['status' => 1, 'msg' => '图片上传失败！'];
    }
    return $litPath;
}

/**
 * 无限级分类
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pk 自增字段（栏目id）
 * @param string $pid parent标记字段
 * @return array
 */
function make_tree($list,$pk='id',$pid='pid',$child='_child',$root=0){
    $tree=array();
    $packData=array();
    foreach ($list as $data){
        $packData[$data[$pk]] = $data;
    }
    foreach ($packData as $key =>$val){
        if($val[$pid]==$root){//代表跟节点
            $tree[]=& $packData[$key];
        }else{
            //找到其父类
            $packData[$val[$pid]][$child][]=& $packData[$key];
        }
    }
    return $tree;
}

/**
 * 遍历数组 并加入依据 pid 的分级信息
 * @param $list
 * @param int $pid
 * @param int $level
 * @param string $html
 */
function get_tree($list, $pid = 0, $level = 0, $html='&nbsp;--'){
    $arr = [];
    foreach($list as $value){
        if($value['pid'] == $pid){
            $value['level'] = $level + 1;
            $value['html'] = str_repeat($html,$level);
            $arr[] = $value;
            $arr = array_merge($arr, get_tree($list, $value['id'], $level + 1, $html));
        }
    }
    return $arr;
}